package com.mine.async.jobexe;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Component
public class DownloadJobRetryHandler {

    private Method getMethod(String sourceClassPath, String methodName, String paramClassPath) throws ClassNotFoundException {
        return ReflectUtil.getMethod(Class.forName(sourceClassPath), methodName, Class.forName(paramClassPath));
    }

    private Object getBean(String sourceClassPath) throws ClassNotFoundException {
        return SpringUtil.getBean(Class.forName(sourceClassPath));
    }

    public boolean handle(String sourceClassPath, String methodName, String paramClassPath, String paramJson) throws ClassNotFoundException {
        Method method = getMethod(sourceClassPath, methodName, paramClassPath);
        Object bean = getBean(sourceClassPath);
        if (ObjectUtil.isNotNull(method) && ObjectUtil.isNotNull(bean)) {
            Object param = BeanUtil.copyProperties(JSONObject.parseObject(paramJson), Class.forName(paramClassPath));
            ReflectUtil.invoke(bean, method, param);
            return true;
        }
        return false;
    }
}
